package cacy.leetcode.linkedList;

/**
 * Project: LeetcodePractice
 * Package: cacy.leetcode.practice20250217
 * Class:   LinkedList05
 * Description:
 *
 * @Date: 2025/2/17 周一
 * @Time: 16:10
 * @Author: 凯齐
 */

// Create new linked list and create each node
class Solution05A {
    public ListNode trainningPlan(ListNode l1, ListNode l2) {
        ListNode res = new ListNode();
        if (l1 == null) {
            if (l2 == null) {
                return null;
            }
            return l2;
        }else {
            if (l2 == null) {
                return l1;
            }
        }
        if (l1.val < l2.val) {
            res.val = l1.val;
            l1 = l1.next;
        }else {
            res.val = l2.val;
            l2 = l2.next;
        }
        ListNode head = res;
        while (l1 != null || l2 != null) {
            if (l1 == null) {
                res.next = l2;
                break;
            }
            if (l2 == null) {
                res.next = l1;
                break;
            }
            ListNode novel = new ListNode();
            if (l1.val < l2.val) {
                novel.val = l1.val;
                l1 = l1.next;
                res.next = novel;
                res = res.next;
            }else {
                novel.val = l2.val;
                l2 = l2.next;
                res.next = novel;
                res = res.next;
            }
        }
        return head;
    }
}

// Create starting node, then connect two linked lists in sequence
class Solution05B {
    public ListNode trainningPlan(ListNode l1, ListNode l2) {
        ListNode start = new ListNode(0), node = start;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                node.next = l1;
                l1 = l1.next;
            }else {
                node.next = l2;
                l2 = l2.next;
            }
            node = node.next;
        }
        node.next = (l1 != null) ? l1 : l2;
        return start.next;
    }
}

public class LinkedList05 {
    public static void main(String[] args) {
        ListNode list1 = new ListNode(1);
        ListNode list2 = new ListNode(-1);
        ListNode res = new Solution05B().trainningPlan(list1, list2);
        while (res != null) {
            System.out.print(res.val + " ");
            res = res.next;
        }
    }
}
